<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
		<meta name="author" content="金西振" />
		<title></title>
		<style>
			.nav-list {
				padding: 0;
				margin: 0;
				list-style: none;
				display: flex;
				line-height: 50px;
				background-color: lightblue;
			}
			.item {
				padding: 0 20px;
			}

			.active {
				color: red;
			}
		</style>
	</head>
	<body>
		<ul class="nav-list">
			<li class="item active">选项1</li>
			<li class="item">选项2</li>
			<li class="item">选项3</li>
			<li class="item">选项4</li>
			<li class="item">选项5</li>
			<li class="item">选项6</li>
		</ul>
		<script>
			var items = document.querySelectorAll('.item');
			var lastIndex = 0;
			// console.log('lastIndex: ', lastIndex);

			for (var i = 0; i < items.length; i++) {
				var item = items[i];
				item.index = i;
				item.onclick = function () {
					// console.log('lastIndex: ', lastIndex);

					items[lastIndex].classList.remove('active');

					// 最终点击谁，让谁变红：添加active类名
					this.classList.add('active');
					lastIndex = this.index;// 记录本次被点击的索引值
				};
			}

		</script>
	</body>
</html>
